package com.ruoyi.system.service.impl;

import java.util.*;
import java.text.SimpleDateFormat;

import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanValidators;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.system.domain.CommunityBusinessTarget;
import com.ruoyi.system.mapper.SysDeptMapper;
import com.ruoyi.system.service.ICommunityBusinessTargetService;
import com.ruoyi.system.service.ISysDeptService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.DevelopmentTopMapper;
import com.ruoyi.system.domain.DevelopmentTop;
import com.ruoyi.system.service.IDevelopmentTopService;

/**
 * 发展量排名Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-08-05
 */
@Service
public class DevelopmentTopServiceImpl implements IDevelopmentTopService 
{
    private static final Logger log = LoggerFactory.getLogger(DevelopmentTop.class);
    @Autowired
    private DevelopmentTopMapper developmentTopMapper;
    @Autowired
    private SysDeptMapper sysDeptMapper;

    @Autowired
    private ICommunityBusinessTargetService communityBusinessTargetService;

    /**
     * 查询发展量排名
     * 
     * @param id 发展量排名主键
     * @return 发展量排名
     */
    @Override
    public DevelopmentTop selectDevelopmentTopById(Long id)
    {
        return developmentTopMapper.selectDevelopmentTopById(id);
    }

    /**
     * 查询发展量排名列表
     * 
     * @param developmentTop 发展量排名
     * @return 发展量排名
     */
    @Override
    @DataScope(deptAlias="d")
    public List<DevelopmentTop> selectDevelopmentTopList(DevelopmentTop developmentTop)
    {
        return developmentTopMapper.selectDevelopmentTopList(developmentTop);
    }

    /**
     * 新增发展量排名
     * 
     * @param developmentTop 发展量排名
     * @return 结果
     */
    @Override
    public int insertDevelopmentTop(DevelopmentTop developmentTop)
    {
        return developmentTopMapper.insertDevelopmentTop(developmentTop);
    }

    /**
     * 修改发展量排名
     * 
     * @param developmentTop 发展量排名
     * @return 结果
     */
    @Override
    public int updateDevelopmentTop(DevelopmentTop developmentTop)
    {
        return developmentTopMapper.updateDevelopmentTop(developmentTop);
    }

    /**
     * 批量删除发展量排名
     * 
     * @param ids 需要删除的发展量排名主键
     * @return 结果
     */
    @Override
    public int deleteDevelopmentTopByIds(Long[] ids)
    {
        return developmentTopMapper.deleteDevelopmentTopByIds(ids);
    }

    /**
     * 删除发展量排名信息
     * 
     * @param id 发展量排名主键
     * @return 结果
     */
    @Override
    public int deleteDevelopmentTopById(Long id)
    {
        return developmentTopMapper.deleteDevelopmentTopById(id);
    }

    /**
     * 导入数据
     */
    @Override
    public String importDevelopmentTop(List<DevelopmentTop> developmentTopList, Boolean isUpdateSupport, String operName)
    {
            if (StringUtils.isNull(developmentTopList) || developmentTopList.size() == 0)
        {
            throw new ServiceException("导入数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (DevelopmentTop developmentTop : developmentTopList)
        {
            try
            {
                // 验证是否存在这个部门
                SysDept sysDepts = sysDeptMapper.selectDeptOnDeptName(developmentTop.getParentDeptName(),developmentTop.getDeptName());

                if (developmentTop.getActivityTime() == null){
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、分部 " + developmentTop.getParentDeptName() + "-小区 " + developmentTop.getDeptName() + " 活动日期格式为：2025-08-15");
                }else {
                    if (StringUtils.isNotNull(sysDepts))
                    {
                        developmentTop.setCreateTime(developmentTop.getActivityTime());
                        developmentTop.setCreateBy(operName);
                        developmentTop.setDeptId(sysDepts.getDeptId());
                        DevelopmentTop developmentTops = developmentTopMapper.selectDevelopmentTopByNameAndDept(developmentTop.getSalesman(), developmentTop.getDeptName(),developmentTop.getActivityTime());
                        if (StringUtils.isNull(developmentTops))
                        {
                            developmentTopMapper.insertDevelopmentTop(developmentTop);
                            successNum++;
                            successMsg.append("<br/>" + successNum + "、业务员 " + developmentTop.getSalesman() + " 导入成功");
                        }else {
                            developmentTop.setId(developmentTops.getId());
                            developmentTopMapper.updateDevelopmentTop(developmentTop);
                            successNum++;
                            successMsg.append("<br/>" + successNum + "、业务员 " + developmentTop.getSalesman() + " 更新成功");
                        }

                    }
                    else
                    {
                        failureNum++;
                        failureMsg.append("<br/>" + failureNum + "、分部 " + developmentTop.getParentDeptName() + "-小区 " + developmentTop.getDeptName() + " 不存在");
                    }
                }

            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、业务员 " + developmentTop.getSalesman() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    @Override
    public List<DevelopmentTop> selectDevelopmentTopListOrder(Long deptId)
    {
        return developmentTopMapper.selectDevelopmentTopListOrder(deptId);
    }

    @Override
    public List<DevelopmentTop> selectDevelopmentTopDetail(Long deptId,String targetTime)
    {
        return developmentTopMapper.selectDevelopmentTopDetail(deptId,targetTime);
    }

    @Override
    public List<Map<String, Object>> selectDevelopmentTop(Long deptId,String targetTime)
    {
        return developmentTopMapper.selectDevelopmentTop(deptId,targetTime);
    }

    @Override
    public List<Map<String, Object>> selectCommunitytotal(Long deptId)
    {
        return developmentTopMapper.selectCommunitytotal(deptId);
    }

    @Override
    public List<DevelopmentTop> getTotal(DevelopmentTop developmentTop) {
        Long businessDeptId = developmentTop.getDeptId();
        if (businessDeptId == null) {
            return java.util.Collections.emptyList();
        }
        
        // 查询营业部信息
        SysDept businessDept = sysDeptMapper.selectDeptById(businessDeptId);
        if (businessDept == null) {
            return java.util.Collections.emptyList();
        }
        
        // 查询营业部下所有小区（含多级子部门）
        java.util.List<SysDept> children = sysDeptMapper.selectChildrenDeptById(businessDeptId);
        java.util.List<Long> communityDeptIds = new java.util.ArrayList<>();
        
        // 添加所有子部门ID
        if (children != null && !children.isEmpty()) {
            communityDeptIds = children.stream()
                    .map(SysDept::getDeptId)
                    .collect(java.util.stream.Collectors.toList());
        }
        
        // 也将营业部自身加入，防止有数据直接挂在营业部上
        communityDeptIds.add(businessDeptId);
        
        if (communityDeptIds.isEmpty()) {
            return java.util.Collections.emptyList();
        }
        
        // 查询这些部门的所有发展量明细数据
        java.util.List<DevelopmentTop> rows;
        if (developmentTop.getCreateTime() != null) {
            rows = developmentTopMapper.selectByDeptIdsAndTime(communityDeptIds, developmentTop.getCreateTime());
        } else {
            rows = developmentTopMapper.selectByDeptIds(communityDeptIds);
        }
        
        if (rows == null || rows.isEmpty()) {
            // 如果没有数据，返回一个空的汇总记录
            DevelopmentTop emptyAgg = new DevelopmentTop();
            emptyAgg.setDeptId(businessDeptId);
            emptyAgg.setDeptName(businessDept.getDeptName());
            emptyAgg.setFullFusion("0");
            emptyAgg.setFttr("0");
            emptyAgg.setBroadband("0");
            emptyAgg.setVideoAi("0");
            emptyAgg.setPoorRepair("0");
            emptyAgg.setTermUp("0");
            emptyAgg.setComboUp("0");
            emptyAgg.setPopAssess("0");
            emptyAgg.setDevelopVolume("0");
            // 设置total字段为全量融合和FTTR的总量
            emptyAgg.setTotal(0L);
            return java.util.Arrays.asList(emptyAgg);
        }
        
        // 计算各个套餐的统计量汇总
        int sumFullFusion = 0;      // 全量融合
        int sumFttr = 0;            // FTTR
        int sumBroadband = 0;       // 宽带
        int sumVideoAi = 0;         // 视频AI
        int sumPoorRepair = 0;      // 质差修复
        int sumTermUp = 0;          // 终端升级
        int sumComboUp = 0;         // 套餐升级
        int sumPopAssess = 0;       // 流量评估
        int sumDevelopVolume = 0;   // 发展量
        
        // 遍历所有明细记录进行求和
        for (DevelopmentTop row : rows) {
            sumFullFusion += parseIntSafe(row.getFullFusion());
            sumFttr += parseIntSafe(row.getFttr());
            sumBroadband += parseIntSafe(row.getBroadband());
            sumVideoAi += parseIntSafe(row.getVideoAi());
            sumPoorRepair += parseIntSafe(row.getPoorRepair());
            sumTermUp += parseIntSafe(row.getTermUp());
            sumComboUp += parseIntSafe(row.getComboUp());
            sumPopAssess += parseIntSafe(row.getPopAssess());
            sumDevelopVolume += parseIntSafe(row.getDevelopVolume());
        }
        
        // 构建汇总结果
        DevelopmentTop agg = new DevelopmentTop();
        agg.setDeptId(businessDeptId);
        agg.setDeptName(businessDept.getDeptName());
        agg.setFullFusion(String.valueOf(sumFullFusion));
        agg.setFttr(String.valueOf(sumFttr));
        agg.setBroadband(String.valueOf(sumBroadband));
        agg.setVideoAi(String.valueOf(sumVideoAi));
        agg.setPoorRepair(String.valueOf(sumPoorRepair));
        agg.setTermUp(String.valueOf(sumTermUp));
        agg.setComboUp(String.valueOf(sumComboUp));
        agg.setPopAssess(String.valueOf(sumPopAssess));
        agg.setDevelopVolume(String.valueOf(sumDevelopVolume));
        // 设置total字段为全量融合和FTTR的总量
        agg.setTotal(Long.valueOf(sumFullFusion + sumFttr));
        
        return java.util.Arrays.asList(agg);
    }

    @Override
    public List<DevelopmentTop> getAllBusinessDepartmentTotals(boolean descending,Long deptId, Date targetTime) {
        // 查询所有营业部
        List<SysDept> businessDepartments = sysDeptMapper.selectBusinessDepartments();
        
        if (businessDepartments == null || businessDepartments.isEmpty()) {
            return java.util.Collections.emptyList();
        }
        
        List<DevelopmentTop> allTotals = new java.util.ArrayList<>();
        
        // 遍历每个营业部，调用getTotal方法
        for (SysDept dept : businessDepartments) {
            DevelopmentTop queryParam = new DevelopmentTop();
            queryParam.setDeptId(dept.getDeptId());
            queryParam.setCreateTime(targetTime);
            
            List<DevelopmentTop> deptTotals = getTotal(queryParam);
            if (deptTotals != null && !deptTotals.isEmpty()) {
                // 设置部门名称
                for (DevelopmentTop total : deptTotals) {
                    total.setDeptName(dept.getDeptName());
                }
                allTotals.addAll(deptTotals);
            }
        }

        // 根据参数决定排序方向：true为从高到低，false为从低到高
        if (descending) {
            allTotals.sort((a, b) -> Long.compare(b.getTotal(), a.getTotal()));
            return allTotals;
        } else {
            // 当descending为false时，特殊处理
            List<DevelopmentTop> zeroList = new java.util.ArrayList<>();
            List<DevelopmentTop> nonZeroList = new java.util.ArrayList<>();
            
            // 分离fttr+全量融合为0和非0的数据
            for (DevelopmentTop total : allTotals) {
                int fttrValue = parseIntSafe(total.getFttr());
                int fullFusionValue = parseIntSafe(total.getFullFusion());
                int sum = fttrValue + fullFusionValue;
                
                if (sum == 0) {
                    zeroList.add(total);
                } else {
                    nonZeroList.add(total);
                }
            }
            
            // 对非0的数据按total从低到高排序，取前10个
            nonZeroList.sort((a, b) -> Long.compare(a.getTotal(), b.getTotal()));
            List<DevelopmentTop> topTenNonZero = nonZeroList.stream()
                    .limit(10)
                    .collect(java.util.stream.Collectors.toList());
            
            // 合并结果：先返回为0的list，再返回前10个非0的list
            List<DevelopmentTop> result = new java.util.ArrayList<>();
            result.addAll(zeroList);
            result.addAll(topTenNonZero);
            
            return result;
        }

//        for (DevelopmentTop developmentTop :allTotals){
//            if (developmentTop.getDeptId() == deptId) {
//                allTotals.remove(developmentTop);
//                allTotals.add(0,developmentTop);
//                break;
//            }
//        }
    }

    @Override
    public List<Map<String, Object>> getSpecificCommunitiesData(String targetTime) {
        try {
            // 固定的四个小区deptId
            List<Long> deptIds = Arrays.asList(180L, 1841L, 1310L, 849L);
            
            // 解析目标时间
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date targetDate = sdf.parse(targetTime);
            
            // 根据部门ID列表和时间精确查询实时发展量数据
            List<DevelopmentTop> developmentList = developmentTopMapper.selectByDeptIdsAndTime(deptIds, targetDate);
            
            // 根据部门ID列表和时间范围查询目标值数据
            List<CommunityBusinessTarget> targetList = communityBusinessTargetService.selectCommunityBusinessTargetByDeptIdsAndTime(deptIds, targetDate);
            
            List<Map<String, Object>> resultList = new ArrayList<>();
            
            for (Long deptId : deptIds) {
                Map<String, Object> communityData = new HashMap<>();
                
                // 从目标数据中获取小区名称和营业部名称
                CommunityBusinessTarget targetData = targetList.stream()
                    .filter(target -> deptId.equals(target.getDeptId()))
                    .findFirst()
                    .orElse(null);
                
                String communityName = targetData != null ? targetData.getCommunityName() : "未知小区";
                String businessDepartment = targetData != null ? targetData.getBusinessDepartment() : "未知营业部";
                
                // 查找该小区的实时发展量数据
                List<DevelopmentTop> communityDevelopment = developmentList.stream()
                    .filter(item -> deptId.equals(item.getDeptId()))
                    .collect(java.util.stream.Collectors.toList());
                
                // 汇总实时发展量
                int totalFullFusion = 0;
                int totalFttr = 0;
                int totalBroadband = 0;
                int totalVideoAi = 0;
                int totalPoorRepair = 0;
                int totalTermUp = 0;
                int totalComboUp = 0;
                int totalPopAssess = 0;
                
                for (DevelopmentTop dev : communityDevelopment) {
                    totalFullFusion += parseIntSafe(dev.getFullFusion());
                    totalFttr += parseIntSafe(dev.getFttr());
                    totalBroadband += parseIntSafe(dev.getBroadband());
                    totalVideoAi += parseIntSafe(dev.getVideoAi());
                    totalPoorRepair += parseIntSafe(dev.getPoorRepair());
                    totalTermUp += parseIntSafe(dev.getTermUp());
                    totalComboUp += parseIntSafe(dev.getComboUp());
                    totalPopAssess += parseIntSafe(dev.getPopAssess());
                }

                
                // 构建返回数据
                communityData.put("communityName", communityName);
                communityData.put("businessDepartment", businessDepartment);
                communityData.put("deptId", deptId);
                
                // 实时发展量
                Map<String, Object> realTimeData = new HashMap<>();
                realTimeData.put("fullFusion", totalFullFusion);
                realTimeData.put("fttr", totalFttr);
                realTimeData.put("broadband", totalBroadband);
                realTimeData.put("videoAi", totalVideoAi);
                realTimeData.put("poorRepair", totalPoorRepair);
                realTimeData.put("termUp", totalTermUp);
                realTimeData.put("comboUp", totalComboUp);
                realTimeData.put("popAssess", totalPopAssess);
                communityData.put("realTimeData", realTimeData);
                
                // 发展目标
                Map<String, Object> targetDataMap = new HashMap<>();
                if (targetData != null) {
                    targetDataMap.put("fullFusionTarget", parseIntSafe(targetData.getConvergenceTarget()));
                    targetDataMap.put("fttrTarget", parseIntSafe(targetData.getFttrTarget()));
                    targetDataMap.put("singleBroadbandTarget", parseIntSafe(targetData.getSingleBroadbandTarget()));
                    targetDataMap.put("videoAiPackage", parseIntSafe(targetData.getVideoAiPackage()));
                    targetDataMap.put("popAssessTarget", parseIntSafe(targetData.getQualityRepair()));
                    targetDataMap.put("oldTerminalUpgrade", parseIntSafe(targetData.getOldTerminalUpgrade()));
                    targetDataMap.put("oldPackageUpgrade", parseIntSafe(targetData.getOldPackageUpgrade()));
                } else {
                    targetDataMap.put("fullFusionTarget", 0);
                    targetDataMap.put("fttrTarget", 0);
                    targetDataMap.put("singleBroadbandTarget", 0);
                    targetDataMap.put("videoAiPackage", 0);
                    targetDataMap.put("popAssessTarget", 0);
                    targetDataMap.put("oldTerminalUpgrade", 0);
                    targetDataMap.put("oldPackageUpgrade", 0);
                }
                communityData.put("targetData", targetDataMap);
                
                // 计算得分（根据新的映射规则和权重）
                double score = calculateCommunityScore(realTimeData, targetDataMap);
                communityData.put("score", score);
                
                resultList.add(communityData);
            }
            
            // 根据得分从高到低排序
            resultList.sort((a, b) -> Double.compare((Double) b.get("score"), (Double) a.get("score")));
            
            return resultList;
            
        } catch (Exception e) {
            log.error("查询指定小区数据失败: {}", e.getMessage());
            return new ArrayList<>();
        }
    }

    private int parseIntSafe(String s) {
        try {
            if (s == null || s.trim().isEmpty()) return 0;
            return Integer.parseInt(s.trim());
        } catch (Exception e) {
            return 0;
        }
    }

    /**
     * 计算小区得分
     * 映射规则：
     * - 视频AI -> 家庭中屏
     * - 老旧套餐升级 -> 移动
     * - 合券量 -> 质差修复
     * 
     * 计算规则：实时量/目标值 * 权重
     * 权重规则：
     * - 融合: 25分
     * - FTTR: 25分
     * - 宽带: 10分
     * - 移动: 5分 (量不超过1.2)
     * - 家庭中屏: 15分
     * - 老旧终端: 10分
     * - 质差修复: 10分
     */
    private double calculateCommunityScore(Map<String, Object> realTimeData, Map<String, Object> targetData) {
        double score = 0.0;
        
        // 融合 25分: 实时量/目标值 * 权重
        int fullFusion = (Integer) realTimeData.get("fullFusion");
        int fullFusionTarget = (Integer) targetData.get("fullFusionTarget");
        if (fullFusionTarget > 0) {
            score += (double) fullFusion / fullFusionTarget * 25;
        }
        
        // FTTR 25分
        int fttr = (Integer) realTimeData.get("fttr");
        int fttrTarget = (Integer) targetData.get("fttrTarget");
        if (fttrTarget > 0) {
            score += (double) fttr / fttrTarget * 25;
        }
        
        // 宽带 10分
        int broadband = (Integer) realTimeData.get("broadband");
        int broadbandTarget = (Integer) targetData.get("singleBroadbandTarget");
        if (broadbandTarget > 0) {
            score += (double) broadband / broadbandTarget * 10;
        }
        
        // 移动 5分 (量不超过1.2) - 映射自老旧套餐升级
        int mobile = (Integer) realTimeData.get("comboUp"); // 老旧套餐升级 -> 移动
        int mobileTarget = (Integer) targetData.get("oldPackageUpgrade");
        if (mobileTarget > 0) {
            double mobileRatio = Math.min((double) mobile / mobileTarget, 1.2); // 量不超过1.2
            score += mobileRatio * 5;
        }
        
        // 家庭中屏 15分 - 映射自视频AI
        int homeScreen = (Integer) realTimeData.get("videoAi"); // 视频AI -> 家庭中屏
        int homeScreenTarget = (Integer) targetData.get("videoAiPackage");
        if (homeScreenTarget > 0) {
            score += (double) homeScreen / homeScreenTarget * 15;
        }
        
        // 老旧终端 10分
        int oldTerminal = (Integer) realTimeData.get("termUp");
        int oldTerminalTarget = (Integer) targetData.get("oldTerminalUpgrade");
        if (oldTerminalTarget > 0) {
            score += (double) oldTerminal / oldTerminalTarget * 10;
        }
        
        // 质差修复 10分 - 映射自合券量
        int qualityRepair = (Integer) realTimeData.get("popAssess"); // 合券量 -> 质差修复
        int qualityRepairTarget = (Integer) targetData.get("popAssessTarget");
        if (qualityRepairTarget > 0) {
            score += (double) qualityRepair / qualityRepairTarget * 10;
        }
        
        return score;
    }

    @Override
    public Map<String, Object> getFourCommunitiesPackageSums(String targetTime) {
        try {
            // 1. 定义四个小区的deptId
            List<Long> deptIds = Arrays.asList(180L, 1841L, 1310L, 849L);

            // 2. 解析时间
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date date = sdf.parse(targetTime);

            // 3. 查询实时发展量
            List<DevelopmentTop> developmentTops = developmentTopMapper.selectByDeptIdsAndTime(deptIds, date);

            // 4. 查询目标数据
            List<CommunityBusinessTarget> communityBusinessTargets = communityBusinessTargetService.selectCommunityBusinessTargetByDeptIdsAndTime(deptIds, date);

            // 5. 计算各项套餐总和
            Map<String, Object> realTimeSums = new HashMap<>();
            realTimeSums.put("fullFusion", developmentTops.stream().mapToInt(dev -> parseIntSafe(dev.getFullFusion())).sum());
            realTimeSums.put("fttr", developmentTops.stream().mapToInt(dev -> parseIntSafe(dev.getFttr())).sum());
            realTimeSums.put("broadband", developmentTops.stream().mapToInt(dev -> parseIntSafe(dev.getBroadband())).sum());
            realTimeSums.put("videoAi", developmentTops.stream().mapToInt(dev -> parseIntSafe(dev.getVideoAi())).sum());
            realTimeSums.put("poorRepair", developmentTops.stream().mapToInt(dev -> parseIntSafe(dev.getPoorRepair())).sum());
            realTimeSums.put("termUp", developmentTops.stream().mapToInt(dev -> parseIntSafe(dev.getTermUp())).sum());
            realTimeSums.put("comboUp", developmentTops.stream().mapToInt(dev -> parseIntSafe(dev.getComboUp())).sum());
            realTimeSums.put("popAssess", developmentTops.stream().mapToInt(dev -> parseIntSafe(dev.getPopAssess())).sum());


            // 6. 计算各项套餐目标总和
            Map<String, Object> targetSums = new HashMap<>();
            targetSums.put("fullFusionTarget", communityBusinessTargets.stream().mapToInt(t -> parseIntSafe(t.getConvergenceTarget())).sum());
            targetSums.put("fttrTarget", communityBusinessTargets.stream().mapToInt(t -> parseIntSafe(t.getFttrTarget())).sum());
            targetSums.put("singleBroadbandTarget", communityBusinessTargets.stream().mapToInt(t -> parseIntSafe(t.getSingleBroadbandTarget())).sum());
            targetSums.put("videoAiPackage", communityBusinessTargets.stream().mapToInt(t -> parseIntSafe(t.getVideoAiPackage())).sum());
            targetSums.put("popAssessTarget", communityBusinessTargets.stream().mapToInt(t -> parseIntSafe(t.getQualityRepair())).sum());
            targetSums.put("oldTerminalUpgrade", communityBusinessTargets.stream().mapToInt(t -> parseIntSafe(t.getOldTerminalUpgrade())).sum());
            targetSums.put("oldPackageUpgrade", communityBusinessTargets.stream().mapToInt(t -> parseIntSafe(t.getOldPackageUpgrade())).sum());


            // 7. 构建返回结果
            Map<String, Object> result = new HashMap<>();
            result.put("realTimeSums", realTimeSums);
            result.put("targetSums", targetSums);

            return result;
        } catch (Exception e) {
            log.error("查询四个小区的各项套餐总和失败: {}", e.getMessage());
            return new HashMap<>();
        }
    }

    @Override
    public List<Map<String, Object>> getSalesmanPackageDetails(Long deptId, String targetTime) {
        return developmentTopMapper.selectSalesmanPackageDetails(deptId, targetTime);
    }
}
